<script setup lang="ts">
import { ref } from "vue";
import { setCurrentLoginUserState } from "@/state/userState";
import { showToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import myAxios from "@/plugins/myAxios";

const userAccount = ref("");
const userPassword = ref("");
const router = useRouter();
const route = useRoute();
const onSubmit = async (values) => {
  const data = await myAxios
    .post("/user/login", {
      userAccount: userAccount.value,
      userPassword: userPassword.value,
    })
    .then(function (response) {
      return response;
    })
    .catch(function (error) {
      // showToast(error.message);
    });
  const { message, description, data: user } = data;
  if (user) {
    showToast("登录成功");
    setCurrentLoginUserState(user);
    router.back();
    // window.location.href = route.query.redirect;
  } else {
    showToast(description.length ? description : message);
  }
};
</script>

<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="userAccount"
        name="用户名"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="userPassword"
        type="password"
        name="密码"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>
</template>

<style scoped></style>
